package cn.itsource.org.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.BaiduAiUtil;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.domain.ShopAuditLog;
import cn.itsource.org.dto.ShopDto;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopAuditLogMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.service.IShopService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 店铺入驻
     * @param shop
     */
    @Override
    @Transactional
    public void settlement(Shop shop) {
        //校验空值
        // StrUtil - hutool工具包中的，有和stringUtils的isBlank方法一样，判断空值
        if (StrUtil.isBlank(shop.getName())) {
            throw new BusinessException("店铺名称不能为空！");
        }
        if (StringUtils.isBlank(shop.getTel())) {
            throw new BusinessException("店铺电话不能为空！");
        }
        if (StringUtils.isBlank(shop.getAddress())) {
            throw new BusinessException("店铺地址不能为空！");
        }
        if (StringUtils.isBlank(shop.getAdmin().getUsername())) {
            throw new BusinessException("管理员姓名不能为空！");
        }
        if (StringUtils.isBlank(shop.getAdmin().getPhone())) {
            throw new BusinessException("管理员电话不能为空！");
        }
        if (StringUtils.isBlank(shop.getAdmin().getEmail())) {
            throw new BusinessException("邮箱不能为空！");
        }
        if (StringUtils.isBlank(shop.getAdmin().getPassword())) {
            throw new BusinessException("密码不能为空！");
        }
        if (StringUtils.isBlank(shop.getLogo())) {
            throw new BusinessException("店铺Logo不能为空！");
        }

        //百度ai审核：审核店铺名称和logo
        if (!BaiduAiUtil.TextCensor(shop.getName())){
            throw new BusinessException("店铺名称不合法！");
        }
        //logo不为null的情况下才审核
        if (!BaiduAiUtil.TextCensor(shop.getLogo())){
            throw new BusinessException("店铺Logo不合法！");
        }

        //校验店铺是否入驻过：判断店铺名称 + 店铺地址
        Shop dbShop = shopMapper.findByNameAndAddress(shop);
        if (dbShop != null){
            throw new BusinessException("该店铺已入驻过，请直接登录！");
        }
        //店铺审核
        //添加到数据库：两张表
        //先添加t_employee
        Employee employee = shop.getAdmin();
        //使用hutool工具包得到随机盐值
        String salt = RandomUtil.randomString(32);
        //将密码和盐值一起加密
        String md5 = SecureUtil.md5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5);
        employee.setState(0); //状态设置为禁用
        //添加到数据库，employee就会生成自增id
        employeeMapper.add(employee);

        //再添加t_shop
        shop.setAdmin_id(employee.getId()); //将employee生成的自增id添加到数据库
        shopMapper.add(shop);
        //再添加shop的id
        employee.setShop_id(shop.getId());
        employeeMapper.update(employee);
        shopMapper.update(shop);
    }

    /** 店铺人工审核 - 审核驳回 */
    @Override
    @Transactional
    public void auditReject(ShopAuditLog log) throws MessagingException {
        //修改审核状态 - 驳回
        // 获取shop对象
        Shop shop = shopMapper.findOne(log.getShopId());
        shop.setState(4); //驳回
        shopMapper.update(shop);

        //添加审核日志
        log.setState(0);
        shopAuditLogMapper.add(log);

        //发送审核失败邮件
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("2097862548@qq.com");
        helper.setSubject("店铺驳回邮件");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h1>你的店铺注册失败！</h1><h3>驳回原因："+ log.getNote() +"</h3>",true);
        //收件人
        helper.setTo("2097862548@qq.com");
        javaMailSender.send(mimeMessage);
    }

    /** 店铺人工审核 - 审核通过 */
    @Override
    @Transactional
    public void auditPass(ShopAuditLog log) throws MessagingException {
        //修改审核状态 - 审核通过待激活
        Shop shop = shopMapper.findOne(log.getShopId());
        shop.setState(2); //审核通过待激活
        shopMapper.update(shop);

        //添加审核日志
        log.setState(1);
        shopAuditLogMapper.add(log);

        //发送激活邮件
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("2097862548@qq.com");
        helper.setSubject("店铺激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h1>你的店铺已注册成功!!!</h1><img src='http://123.207.27.208"+ shop.getLogo() +"' >" +
                "<a href='http://127.0.0.1:8080/shop/active/"+ log.getShopId() +"'>点击该链接激活店铺</a>",true);
        Employee employee = employeeMapper.findOne(shop.getAdmin_id());
        //收件人
        helper.setTo(employee.getEmail());
        javaMailSender.send(mimeMessage);
    }

    /** 店铺人工审核 - 激活邮件 */
    @Override
    public void active(Long id) {
        //修改店铺状态
        Shop shop = shopMapper.findOne(id);
        shop.setState(3); //激活成功
        shopMapper.update(shop);
    }

    @Override
    public List<ShopDto> echarts() {
        return shopMapper.echarts();
    }
}
